from selenium import webdriver

# 创建浏览器对象
driver = webdriver.Chrome()
# 窗口最大化
driver.maximize_window()
# 打开特定网页
driver.get("https://www.baidu.com")

# 常用操作和属性
# 获取网页源代码
# print(driver.page_source)
# with open("baidu.html", "w", encoding="utf-8") as f:
#     f.write(driver.page_source)

# 获取单个cookie
# print(driver.get_cookie("BAIDUID"))
cookie_str = ""
cookie_dict = {}
for cookie in driver.get_cookies():
    key = cookie.get("name")
    value = cookie.get("value")
    cookie_str += f"{key}={value};"
    cookie_dict[key] = value
print(cookie_str)
print(cookie_dict)

# 整个可视窗口截图
driver.save_screenshot("baidu.png")
# 截取特定区域
div_element = driver.find_element("xpath","//div[@id='lg']")
div_element.screenshot("baidu_div.png")

# find_element 的xpath只能获取到元素 不能直接获取文本或属性
print(div_element.text)
print(div_element.get_attribute("class"))

# 关闭浏览器
driver.quit()